﻿Imports iTextSharp
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports iTextSharp.text.xml
Imports System.IO
Module FormMethods
    Public Sub GeneratePdfs(ByVal DestinationFileName As String, ByVal PdfFormTemplateLocation As String, ByVal ExportDestination As String, ByVal LoadedCsv As CsvConnector, ByVal DataSourceTable As DataTable)
        Dim MyTemplate As New PdfTemplateInfo(PdfFormTemplateLocation, DestinationFileName, ExportDestination)
        If IsLoadedCSVCompatible(MyTemplate, LoadedCsv) Then
            ProcessGridView(MyTemplate, LoadedCsv, DataSourceTable)
        End If
    End Sub

    Private Sub ProcessGridView(ByVal PdfTmplt As PdfTemplateInfo, ByVal PdfCsv As CsvConnector, ByVal PdfDataTable As DataTable)
        Dim gridDt As New DataTable
        gridDt = PdfDataTable

        Dim dr As DataRow
        Dim TemplateFieldStr As String
        Dim RowNumber As Int32 = 0

        Dim PdfReader As PdfReader
        Dim PdfStamper As PdfStamper
        Dim PdfFormFields As AcroFields

        For Each dr In gridDt.Rows
            RowNumber += 1
            PdfReader = New PdfReader(PdfTmplt.FileLocation)
            PdfStamper = New PdfStamper(PdfReader, New FileStream(PdfTmplt.DestinationPath & "\" & PdfTmplt.ExportedFileName & "_" & RowNumber & ".pdf", FileMode.Create))
            PdfFormFields = PdfStamper.AcroFields

            For Each TemplateFieldStr In PdfTmplt.FieldList
                If Not IsNothing(dr.Item(TemplateFieldStr)) Then
                    PdfFormFields.SetField(TemplateFieldStr, dr.Item(TemplateFieldStr))
                End If
            Next
            PdfStamper.FormFlattening = True
            PdfStamper.Close()
            PdfReader.Close()
        Next

    End Sub

    Private Function IsLoadedCSVCompatible(ByVal PdfTmplt As PdfTemplateInfo, ByVal PdfCsv As CsvConnector) As Boolean

        For Each de As String In PdfTmplt.FieldList
            If Not PdfCsv.SourceDt.Columns.Contains(de) Then
                Return False
            End If
        Next

        Return True
    End Function
End Module
